#include "Stdafx.h"
#include "HttpResponse.h"
#include "Helper.h"

#include "StreamWrappers.h"

#include "poco/Net/HTTPServerResponse.h"

namespace MiniHttpServer
{
	HttpResponse::HttpResponse( Poco::Net::HTTPServerResponse& response )
		: m_response(response)
		, m_headers(gcnew System::Collections::Specialized::NameValueCollection())
		, m_contentLength(-1)
		, m_keepAlive(true)
		, m_status(System::Net::HttpStatusCode::OK)
		, m_chunked(false)
	{
		for (auto iter = m_response.begin(); iter != m_response.end(); iter++)
		{
			m_headers->Add(gcnew System::String(iter->first.c_str()), gcnew System::String(iter->second.c_str()));
		};
	}

	HttpResponse::~HttpResponse()
	{
		this->!HttpResponse();
	}

	HttpResponse::!HttpResponse()
	{
	}


	void HttpResponse::PrepareHeaders()
	{
		for (int i = 0; i < m_headers->Count; i++)
		{
			array<System::String^>^ values = m_headers->GetValues(i);
			for (int j = 0; j < values->Length; j++)
			{
				m_response.set(StringToString(m_headers->GetKey(i)).c_str(), StringToString(values[j]).c_str());
			}
		}

		if ((m_contentType != nullptr) && (m_contentType->Length > 0))
		{
			m_response.setContentType(StringToString(m_contentType));
		}

		if (m_contentLength >= 0)
			m_response.setContentLength(m_contentLength);
		m_response.setChunkedTransferEncoding(m_chunked || (m_contentLength < 0));

		m_response.setKeepAlive(m_keepAlive);
		m_response.setStatusAndReason(static_cast<Poco::Net::HTTPResponse::HTTPStatus>(m_status));
	}

	System::IO::Stream^ HttpResponse::GetBody()
	{
		if (!m_responseStream)
		{
			PrepareHeaders();
			m_responseStream = gcnew OutputStreamWrapper(m_response.send());
		}
		return m_responseStream;
	}

	void HttpResponse::SetStatus( System::Net::HttpStatusCode status )
	{
		m_status = status; 
		m_response.setStatusAndReason(static_cast<Poco::Net::HTTPResponse::HTTPStatus>(status));
	}

	System::String^ HttpResponse::GetStatusDescription()
	{
		return gcnew System::String(
			Poco::Net::HTTPResponse::getReasonForStatus(
			static_cast<Poco::Net::HTTPResponse::HTTPStatus>(
			m_status
			)
			).c_str());
	}

	void HttpResponse::AddHeaderValue( System::String^ strKey, System::String^ strValue )
	{
		m_headers->Add(strKey, strValue);
	}

};